package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.dto.MedicinestorehouseDTO;
import city.spring.modules.medicine.entity.MedicinestorehouseEntity;
import city.spring.modules.medicine.service.MedicinestorehouseService;
import city.spring.modules.medicine.vo.MedicinestorehouseVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/medicinestorehouse")
public class MedicinestorehouseController extends ApiController {
    /**
     * <strong>仓库设置</strong> Service
     */
    private final MedicinestorehouseService medicinestorehouseService;
    private final EmployeeService employeeService;
    /**
     * 实体类（仓库设置）可排序字段
     */
    private final List<SFunction<MedicinestorehouseEntity, ?>> entityOrderFields;

    public MedicinestorehouseController(MedicinestorehouseService medicinestorehouseService, EmployeeService employeeService) {
        this.medicinestorehouseService = medicinestorehouseService;
        this.employeeService = employeeService;
        this.entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicinestorehouseEntity::getId);
        entityOrderFields.add(MedicinestorehouseEntity::getSname);
        entityOrderFields.add(MedicinestorehouseEntity::getAddress);
        entityOrderFields.add(MedicinestorehouseEntity::getUserId);
        entityOrderFields.add(MedicinestorehouseEntity::getGmtCreate);
        entityOrderFields.add(MedicinestorehouseEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>仓库设置</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MedicinestorehouseEntity entity) {
        LambdaQueryChainWrapper<MedicinestorehouseEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        List<MedicinestorehouseEntity> list = lambdaQuery.list();
        return success(list);

    }

    /**
     * 分页获取 <strong>仓库设置</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MedicinestorehouseVO entity) {

        QueryWrapper<? extends MedicinestorehouseEntity> queryWrapper = buildQuery(entity);
        return success(medicinestorehouseService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MedicinestorehouseEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicinestorehouseEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicinestorehouseEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUserId());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUserId(null);
//                record.setName("< 找不到管理员 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>仓库设置</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

        QueryWrapper<MedicinestorehouseVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicinestorehouseVO> records = medicinestorehouseService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(medicinestorehouseService.getById(id));
    }

    /**
     * 添加一个 <strong>仓库设置</strong>
     *
     * @param entity 新增的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicinestorehouseDTO entity) {
        medicinestorehouseService.saveStorehouse(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }


    /**
     * 修改一个 <strong>仓库设置</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicinestorehouseEntity entity) {
        medicinestorehouseService.lambdaUpdate()
                .set(MedicinestorehouseEntity::getId, entity.getId())
                .set(MedicinestorehouseEntity::getSname, entity.getSname())
                .set(MedicinestorehouseEntity::getAddress, entity.getAddress())
                .set(MedicinestorehouseEntity::getUserId, entity.getUserId())
                .set(MedicinestorehouseEntity::getDescription, entity.getDescription())
                .set(MedicinestorehouseEntity::getStype, entity.getStype())
                .eq(MedicinestorehouseEntity::getId, id)
                .update();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>仓库设置</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicinestorehouseService.removeById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>仓库设置</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicinestorehouseService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>仓库设置</strong>
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicinestorehouseEntity> buildLambdaQuery(MedicinestorehouseEntity entity) {
        LambdaQueryChainWrapper<MedicinestorehouseEntity> lambdaQuery = medicinestorehouseService.lambdaQuery();
        lambdaQuery.like(entity.getId() != null, MedicinestorehouseEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSname()), MedicinestorehouseEntity::getSname, entity.getSname());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getAddress()), MedicinestorehouseEntity::getAddress, entity.getAddress());
        return lambdaQuery;
    }

    /**
     * 获取仓库管理员名称
     *
     * @return
     */
    @GetMapping("/getStorehouseAllAndName")
    public Object getStorehouseAllAndName() {
        return success(medicinestorehouseService.getStorehouseAllAndName());
    }

    /**
     * 获取仓库类型为 药库 的仓库 列表展示
     *
     * @return
     */
    @GetMapping("/getStorehouseByStypeIsMedicine")
    public Object getStorehouseByStypeIsMedicine() {
        return success(medicinestorehouseService.getStorehouseByStypeIsMedicine());
    }


    /**
     * 获取仓库类型为 药库 的仓库 分页展示
     *
     * @param pageable
     * @return
     */
    @GetMapping("/getStorehouseStypeIsMedicine")
    public Object getStorehouseStypeIsMedicine(Pageable pageable) {
        return success(medicinestorehouseService.getStorehouseStypeIsMedicine(pageable));
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinestorehouseEntity> buildQuery(MedicinestorehouseVO entity) {
        QueryWrapper<MedicinestorehouseEntity> wrapper = new QueryWrapper<>();
        wrapper.like(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(entity.getUserId() != null, "t1.user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t2.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t1.sname", entity.getSname());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

}
